/*
 * @(#)DateUtil.java
 *
 * @Company <Jinher Technology Development Company LTD.>
 */

package com.cn.system.common.util;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.Locale;
import java.util.TimeZone;

import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public  class DateUtil{
	
  protected static Logger logger = LoggerFactory.getLogger(DateUtil.class);
  public DateUtil(){
	  
  }
  public static boolean isSameDay(Date date1, Date date2)
  {
    return DateUtils.isSameDay(date1, date2);
  }

  public static boolean isSameDay(Calendar cal1, Calendar cal2) {
    return DateUtils.isSameDay(cal1, cal2);
  }

  public static boolean isSameInstant(Date date1, Date date2) {
    return DateUtils.isSameInstant(date1, date2);
  }

  public static boolean isSameInstant(Calendar cal1, Calendar cal2) {
    return DateUtils.isSameInstant(cal1, cal2);
  }

  public static boolean isSameLocalTime(Calendar cal1, Calendar cal2) {
    return DateUtils.isSameLocalTime(cal1, cal2);
  }

  public static Date parseDate(String str, String[] parsePatterns) throws ParseException
  {
    return DateUtils.parseDate(str, parsePatterns);
  }

  public static Date StringToDate(String mydate)
  {
    Date tempDate = new Date();
    if (mydate.equals(""))
      tempDate = null;
    else {
      SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
      try {
        tempDate = dateformat.parse(mydate);
      } catch (ParseException e) {
        e.printStackTrace();
      }
    }
    return tempDate;
  }

  public static Date round(Date date, int field) {
    return DateUtils.round(date, field);
  }

  public static Calendar round(Calendar date, int field) {
    return DateUtils.round(date, field);
  }

  public static Date round(Object date, int field) {
    return DateUtils.round(date, field);
  }

  public static Date truncate(Date date, int field) {
    return DateUtils.truncate(date, field);
  }

  public static Calendar truncate(Calendar date, int field) {
    return DateUtils.truncate(date, field);
  }

  public static Date truncate(Object date, int field) {
    return DateUtils.truncate(date, field);
  }

  @SuppressWarnings("unchecked")  
  public static Iterator iterator(Date focus, int rangeStyle)
  {
    return DateUtils.iterator(focus, rangeStyle);
  }
  @SuppressWarnings("unchecked")
  public static Iterator iterator(Calendar focus, int rangeStyle)
  {
    return DateUtils.iterator(focus, rangeStyle);
  }
  @SuppressWarnings("unchecked")
  public static Iterator iterator(Object focus, int rangeStyle)
  {
    return DateUtils.iterator(focus, rangeStyle);
  }

  public static String formatUTC(long millis, String pattern) {
    return DateFormatUtils.formatUTC(millis, pattern);
  }

  public static String formatUTC(Date date, String pattern) {
    return DateFormatUtils.formatUTC(date, pattern);
  }

  public static String formatUTC(long millis, String pattern, Locale locale) {
    return DateFormatUtils.formatUTC(millis, pattern, locale);
  }

  public static String formatUTC(Date date, String pattern, Locale locale) {
    return DateFormatUtils.formatUTC(date, pattern, locale);
  }

  public static String format(long millis, String pattern) {
    return DateFormatUtils.format(millis, pattern);
  }

  public static String format(Date date, String pattern) {
    if (date == null)
      return "";
    return DateFormatUtils.format(date, pattern);
  }

  public static String format(long millis, String pattern, TimeZone timeZone) {
    return DateFormatUtils.format(millis, pattern, timeZone);
  }

  public static String format(Date date, String pattern, TimeZone timeZone) {
    return DateFormatUtils.format(date, pattern, timeZone);
  }

  public static String format(long millis, String pattern, Locale locale) {
    return DateFormatUtils.format(millis, pattern, locale);
  }

  public static String format(Date date, String pattern, Locale locale) {
    return DateFormatUtils.format(date, pattern, locale);
  }

  public static String format(long millis, String pattern, TimeZone timeZone, Locale locale)
  {
    return DateFormatUtils.format(millis, pattern, timeZone, locale);
  }

  public static String format(Date date, String pattern, TimeZone timeZone, Locale locale)
  {
    return DateFormatUtils.format(date, pattern, timeZone, locale);
  }

  public static String format(String pattern) {
    return format(new Date(), pattern);
  }
  public static Date parseDate(String dateString, String DataFormat) {
		SimpleDateFormat fordate = new SimpleDateFormat(DataFormat);
		if (dateString == null || dateString.equals(""))
			return null;
		try {

			return fordate.parse(dateString);
		} catch (ParseException e) {
			logger.error(e.getMessage());
		}
		return null;
	}

  public static final String getCurrentTime() {
		long time = Calendar.getInstance().getTimeInMillis();
		return DateFormatUtils.format(time, "yyyy-MM-dd HH:mm:ss");
	}

	public static final String getCurrentTime(Date d) {
		return DateFormatUtils.format(d, "yyyy-MM-dd HH:mm:ss");
	}

	public static final String getCurrentDate() {
		long time = Calendar.getInstance().getTimeInMillis();
		return DateFormatUtils.format(time, "yyyy-MM-dd 00:00:00");
	}

	public static final String getCurrentDate(Date d) {
		return DateFormatUtils.format(d, "yyyy-MM-dd 00:00:00");
	}

	public static final String getCurrentDateShortStyle() {
		long time = Calendar.getInstance().getTimeInMillis();
		return DateFormatUtils.format(time, "yyyy-MM-dd");
	}

	public static final String getCurrentDateShortStyle(Date d) {
		return DateFormatUtils.format(d, "yyyy-MM-dd");
	}

	public static final String shortStyle(String longStyleDate) {
		if (longStyleDate == null || "".equals(longStyleDate))
			return "0000-00-00";
		return longStyleDate.substring(0, 10);
	}

	public static final String longStyle(String shortStyleDate) {
		if (shortStyleDate == null || "".equals(shortStyleDate))
			return "0000-00-00 00:00:00";
		return shortStyleDate + " 00:00:00";
	}
	public static final String getCurrentYear(){
		long time = Calendar.getInstance().getTimeInMillis();
		return DateFormatUtils.format(time, "yyyy");
	}
	
	/** 根据时间变量返回时间字符串
	 * @return 返回时间字符串
	 * @param pattern 时间字符串样式
	 * @param date 时间变量
	 */
	public static String dateToString(Date date, String pattern)
	{

		if (date == null)
		{

			return null;
		}

		try
		{

			SimpleDateFormat sfDate = new SimpleDateFormat(pattern);
			sfDate.setLenient(false);

			return sfDate.format(date);
		}
		catch (Exception e)
		{

			return null;
		}
	}
	
	/** 返回当前时间
	 * @return 返回当前时间
	 */
	public static Date getCurrentDateTime()
	{
		java.util.Calendar calNow = java.util.Calendar.getInstance();
		java.util.Date dtNow = calNow.getTime();

		return dtNow;
	}
	/**
	 * 根据传入时间值 进行格式化 格式（**天**小时**分钟**秒）
	 * @param milliseconds
	 * @return
	 */
	public static String formatLongTime(long milliseconds ) {
		StringBuffer result = new StringBuffer();
		long days =0;
		long hours =0;
		long minutes = 0;
        double seconds = milliseconds/1000d;
        DecimalFormat df = new DecimalFormat("#.0"); 
        df.setRoundingMode(RoundingMode.HALF_UP);  
		if( seconds >= 60 ) {
			minutes = (long)seconds/60;
			seconds = seconds%60;
		} 
		seconds = Double.valueOf(df.format(seconds));
		if( minutes >= 60 ) {
			hours = minutes/60;
			minutes = minutes%60;
		}
		if( hours >= 24 ) {
			days = hours/24;
			hours = hours%24;
		}
		if( days > 0 ) {
			result.append( days +"天" );
		}
		if( hours > 0 || days > 0 ) {
			result.append( hours + "小时" );
		}
		if( minutes > 0 || hours> 0 || days >0 ) {
			result.append( minutes + "分钟" );
		}
		if( seconds > 0 || minutes > 0 || hours> 0 || days >0 ) {
			result.append( seconds + "秒" );
		}
		if( "".equals( result.toString() ) ) {
			result.append("0秒");
		}
		
		return result.toString();
	}
	
	/**
	 * 
	 * @param date
	 * @return
	 */
	public static Date convertStr2Date(String date){
		SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//String str = formatDate.format(date);
		Date time = null;
		try {            
			time = formatDate.parse(date.trim());
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return time;
	}
	public static void main( String[] args ) {
		//System.out.println( formatLongTime(2L));
		try {
			String s="10:00:31";
			SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");//yyyy-MM-dd HH:mm:ss
			Date d=sdf.parse(s);
			System.out.println(d);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 比较两个时间段是否有交集,true:有交集,false:没有交集
	 * @param compare1 待比较的第一个时间段,数组内前面是较大的时间,后面是较小的时间,时间格式为HH:mm
	 * @param compare2 待比较的第二个时间段,数组内前面是较大的时间,后面是较小的时间,时间格式为HH:mm
	 * @return
	 */
	public static boolean checkTimeConflict(String[]compare1,String[]compare2){
		boolean b=false;
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");//yyyy-MM-dd HH:mm:ss
		//1.插入时间的开始时间小于已经存在的一段时间的开始时间，但结束时间位于开始时间和结束时间之间(重叠)
		//2.插入时间的开始时间小于已经存在的一段时间的开始时间，但结束时间大于结束时间(全包含)
		//3.插入时间的开始时间大于一段已经存在的时间的开始时间，但是却小于这段时间的结束时间,且结束时间大于这段时间的
		try {
			Date c1Begin=sdf.parse(compare1[0]);
			Date c1End=sdf.parse(compare1[1]);
			Date c2Begin=sdf.parse(compare2[0]);
			Date c2End=sdf.parse(compare2[1]);
			if(c1Begin.getTime()<c2Begin.getTime()){
				if(c1End.getTime()>c2Begin.getTime() && c1End.getTime()<c2End.getTime()){//1
					b=true;
					return b;
				}else if(c1End.getTime()>c2End.getTime()){//2全包含
					b=true;
					return b;
				}
			}
			if(c1Begin.getTime()>c2Begin.getTime()&& c1Begin.getTime()<c2End.getTime()){//3
				b=true;
				return b;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return b;
	}
	
	public static final String getCurrentMonth(Date d) {
		return DateFormatUtils.format(d, "yyyyMMdd");
	}
	
	public static final String getYYYYMMDDHHMMSS() {
		long time = Calendar.getInstance().getTimeInMillis();
		return DateFormatUtils.format(time, "yyyyMMddHHmmss");
	}
	
	public static final String getCurrentMonth2(){
		long time = Calendar.getInstance().getTimeInMillis();
		return DateFormatUtils.format(time, "yyyy-MM");
	}
	
	/**
	 * 获取今天的日期:如YYYY年MM月DD日
	 * 
	 * @return
	 */
	public static String getCurrentDateChs() {
		String[] fullDateStr = DateUtil.getCurrentDateShortStyle().split("-");
		String today = fullDateStr[0] + "年" + fullDateStr[1] + "月"
				+ fullDateStr[2] + "日";
		return today;
	}
	
	/**
	 * 获取当前月的第一天
	 * @return
	 */
	public static final String getCurrentMonthFirstDay(){
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		//获取前月的第一天
		Calendar cal=Calendar.getInstance();//获取当前日期 
		cal.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天 
		String firstDay = format.format(cal.getTime());
		return firstDay;
	}
	
	/**
	 * 获取当前月最后一天
	 * @return
	 */
	public static final String getCurrentMonthLastDay(){
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.MONTH, 1);
		cal.set(Calendar.DAY_OF_MONTH,0);//设置为1号,当前日期既为本月第一天 
		String lastDay = format.format(cal.getTime());
		return lastDay;
	}
	
	public static final String getCurrentMonth(){
		long time = Calendar.getInstance().getTimeInMillis();
		return DateFormatUtils.format(time, "yyyyMM");
	}
	
	public static final String getStartDateShortStyle() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, 1);
		return  DateFormatUtils.format(calendar.getTime(), "yyyy-MM-dd");
	}
	
}